#! /bin/bash
# empty the given relations from database foge

# args: [pguser]

if [ $# -lt 1 ]  
then
    echo "Args: pguser enquiry answertable [sectiontable...]" 1>&2
    echo "Empties the FOGE script's db relations" 1>&2
    echo "pguser may be the empty string" 1>&2
    echo "Args: -c pguser" 1>&2
    echo "Execute the SQL statements on stdin" 1>&2
    exit 1
fi

if [ "$1" = '-c' ]
then
    docreate=1
    shift
fi

pguser="$1"

if [ "$pguser" != "" ]
then
    psql="psql -d foge -U '$pguser'"
else
    psql="psql -d foge"
fi

if [ "$docreate" ]
then
    $psql
    exit 0
fi

enquir="$2"
answer="$3"
shift 3

fmtsec="    delete from %s;\n";
fmtans="    delete from %s where name='%s';\n"

{
    echo "begin;"
    for rel in "$@"
    do
	printf "$fmtsec" $rel
    done
    printf "$fmtans" $answer $enquir
    echo "commit;"
} | $psql
